package edu.washington.ling.syntric.consistency;

import java.util.LinkedList;
import java.util.List;

import edu.washington.ling.syntric.struct.tree.Token;
import edu.washington.ling.syntric.struct.tree.Tree;

public class RelativeClauseRule extends ConsistencyRule {

	@Override
	public void apply(Tree ds) {
		Token dsRoot = ds.getDSRoot();
		apply(dsRoot, ds);
	}

	public void apply(Token t, Tree ds) {
		
		// Diagnostic test pt 1
		if (t.getTag().equals("VM") && (t.hasDSHead())) {
			// Diagnostic test pt 2
			if (t.getDSRelation().endsWith("relc")) {
				// Operation					
				
				// Get parent of the relative clause
				Token parent = t.getDSHead();
				
				// Remove relative clause as child of parent
				parent.removeDSDependent(t);
				
				// Create an COMP EC and attach it as a child of the parent
				Token compEC = ConsistencyUtils.createBaseEC("COMP", t.getDSRelation());
				parent.addDSDependent(compEC);
				compEC.setDSHead(parent);
				
				// Set COMP EC as parent of the relative clause, change relation to "ccof"
				compEC.addDSDependent(t);
				t.setDSHead(compEC);
				t.setDSRelation("ccof");
				
				// Insert COMP EC into position left of the relative clause's span
				// TODO: Compromise
				// This should really be to the left of the relative clause's 
				// maximum contiguous span, in case there has been any long-distance 
				// scrambling 
				OrderUtils.insertLeftOfSpan(compEC, t, ds);
			}
		}
		// This rule adds an EC in between the triggering node and its 
		// parent, so will change that parent's list of children. Therefore
		// when applying to children it must apply to a copy of the list
		List<Token> copyOfChildren = new LinkedList<Token>(t.getDSDependents());
		for (Token child: copyOfChildren) {
			apply(child, ds);
		}
	}
}
